
package com.filetransfer.server.message;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.filetransfer.config.ReceiveFileMessageConfig;
import com.filetransfer.global.ThreadPoolFactory;
import com.filetransfer.util.LogUtil;



/**
 * 功能说明:  <br>
 * 开发人员: hanxuetong <br>
 * 开发时间: 2014-7-28 <br>
 * ======== ====== ============================================ <br>
 * 
 */
public class ReceiveFileMessageServer {

	// private int bindPort;    //默认监听端口号为222 
     private ServerSocket serverSocket;      //服务套接字等待对方的连接和文件发送      
     private ExecutorService executorService;    //线程池  
     //private final int POOL_SIZE = 1;            //单个CPU的线程池大小 
	
     private ReceiveFileMessageConfig receiveFileMessageConfig;
     
/*     *//** 
      * 不带参数的构造器，选用默认的端口号 
      * @throws Exception 
      *//*  
     public ReceiveFileMessageServer() throws Exception{  
         try {  
             this.bingToServerPort(bindPort);  
             creatThreadPool();  
         } catch (Exception e) {  
             throw new Exception("绑定端口不成功!");  
         }  
     }  */
       
     /** 
      * 带参数的构造器，选用用户指定的端口号 
      * @param port 
      * @throws Exception 
      */  
     public ReceiveFileMessageServer(ReceiveFileMessageConfig receiveFileMessageConfig) throws Exception{  
         try {  
        	 this.receiveFileMessageConfig=receiveFileMessageConfig;
             this.bingToServerPort(receiveFileMessageConfig.getBindPort()); 
            
             creatThreadPool();  
         } catch (Exception e) {  
             throw new Exception("绑定端口不成功!");  
         }  
     } 
     
     private void creatThreadPool()
 	{
 		//   executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE); 
 		// executorService = Executors.newFixedThreadPool( POOL_SIZE);  
    	 executorService=ThreadPoolFactory.getExecutorServiceReceiveMessage();
 		// System.out.println("接收消息线程数 ： " +  POOL_SIZE); 
 	}
     
     
     
     private void bingToServerPort(int port) throws Exception{  
         try {  
             serverSocket = new ServerSocket(port);  
           
             System.out.println("消息接收服务启动! 端口为"+port);  
         } catch (Exception e) {
        	 LogUtil.err("启动消息接收服务失败，端口"+port+"被占用！", e);
            throw new RuntimeException("启动消息接收服务失败，端口"+port+"被占用！");
        	 
         }  
     }  
     
     
	  public void service() {  
	        
		  Socket socket = null;  
          while (true) {  
              try {  
                  socket = serverSocket.accept();  
                  System.out.println("socket接收！！");
                  executorService.execute(new ReceiveFileMessageHandle(socket,receiveFileMessageConfig));  
              } catch (Exception e) {  
                  e.printStackTrace();  
              }  
          }  
		  
      } 
     
     
}
